package com.zmj.base.file.service;

import cn.hutool.core.util.StrUtil;
import com.zmj.base.file.util.MinIoUntil;
import io.minio.MinioClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import java.io.InputStream;

@Slf4j
@Service
public class MinIoFileService implements IFileService {
    private static final String IO_TYPE = "minio";

    @Value("${minio.endpoint}")
    private String endpoint;
    @Value("${minio.endpoint_ex}")
    private String endpointEx;
    @Value("${minio.accessKey}")
    private String accessKey;
    @Value("${minio.secretKey}")
    private String secretKey;
    @Value("${minio.bucketName}")
    private String bucketName;

    private MinioClient minioClient;

    @Override
    public String getIoType() {
        return IO_TYPE;
    }

    @PostConstruct
    public void init() {
        // 校验bucketName是否已经存在，否则自动创建
        MinIoUntil minIoUntil = new MinIoUntil();
        minioClient = minIoUntil.getClient(endpoint, accessKey, secretKey);
        boolean b = false;
        try {
            // 判断是否存在Bucket
            if (!minioClient.bucketExists(bucketName)) {
                minioClient.makeBucket(bucketName);
            }
//            // 检查策略
//            PolicyType policyType = minioClient.getBucketPolicy(bucketName, "*");
//            if (null == policyType) {
//                policyType = PolicyType.READ_ONLY;
//                minioClient.setBucketPolicy(bucketName, "*", policyType);
//            }
        } catch (Exception e) {
            log.error("初始化失败", e);
        }
    }

    /**
     * 文件上传
     *
     * @return
     */
    @Override
    public String saveItem(String parentPath, MultipartFile file) {
        String fileName = "";
        String nativeName = file.getOriginalFilename();
        nativeName = nativeName.substring(nativeName.lastIndexOf(".")+1);
        if(StrUtil.isNotEmpty(parentPath)) {
            fileName = parentPath+"/"+System.currentTimeMillis() + "." + nativeName;
        } else {
            fileName = System.currentTimeMillis() + "." + nativeName;
        }
        String filePath = fileName;
        String viewPath = "";
        try {
            MinIoUntil minIoUntil = new MinIoUntil();
            viewPath = minIoUntil.putFile(minioClient, endpoint, bucketName, filePath, file);
            viewPath = viewPath.replaceAll(endpoint, endpointEx);
        } catch (Exception e) {
            throw new RuntimeException("上传文件失败！");
        }
        return viewPath;
    }

    /**
     * 下载文件
     * @param url
     * @return
     */
    @Override
    public InputStream download(String url) {
        String objectName = StrUtil.replace(url,endpoint + "/" + bucketName,"");
        try {
            MinIoUntil minIoUntil = new MinIoUntil();
            InputStream inputStream = minioClient.getObject(bucketName, objectName);
            return inputStream;
        } catch (Exception e) {
            log.error("下载失败", e);
            throw new RuntimeException("获取文件失败！");
        }
    }

    /**
     * 删除文件
     * @param url
     * @return
     */
    @Override
    public boolean deleteFile(String url) {
        String objectName = StrUtil.replace(url,endpoint + "/" + bucketName,"");
        try {
            MinIoUntil minIoUntil = new MinIoUntil();
            minIoUntil.deleteFile(minioClient,bucketName,objectName);
            return true;
        } catch (Exception e) {
            log.error("删除文件失败", e);
            throw new RuntimeException("删除文件失败！");
        }
    }
}
